<script setup lang="tsx">
import { ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useRouteStore } from '@/store/modules/route';
import { fetchDeleteMenu, fetchGetMenuList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table-no-pagenation';
import { yesOrNoRecord } from '@/constants/common';
import { enableStatusRecord, menuTypeRecord } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import MenuOperateModal, { type OperateType } from './modules/menu-operate-modal.vue';

const appStore = useAppStore();

const { bool: visible, setTrue: openModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);

const { columns, columnChecks, data, loading, getData } = useTable({
  apiFn: fetchGetMenuList,
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'menuName',
      title: '菜单名称',
      align: 'left',
      titleAlign: 'left',
      minWidth: 120
    },
    {
      key: 'menuType',
      title: '菜单类型',
      align: 'center',
      width: 120,
      render: row => {
        const tagMap: Record<ManageApi.MenuManage.MenuType, NaiveUI.ThemeColor> = {
          0: 'default',
          1: 'primary'
        };
        const label = menuTypeRecord[row.menuType];
        return <NTag type={tagMap[row.menuType]}>{label}</NTag>;
      }
    },
    {
      key: 'icon',
      title: '图标',
      align: 'center',
      width: 60,
      render: row => (
        <div class="flex-center">
          <SvgIcon localIcon={row.meta?.localIcon} class="text-icon" />
        </div>
      )
    },
    {
      key: 'routeName',
      title: '路由名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'path',
      title: '路由路径',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: '菜单状态',
      align: 'center',
      width: 80,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Map<Api.Common.EnableStatus, NaiveUI.ThemeColor> = new Map([
          [true, 'success'],
          [false, 'warning']
        ]);
        const label = enableStatusRecord.get(row.status);

        return <NTag type={tagMap.get(row.status)}>{label}</NTag>;
      }
    },
    {
      key: 'hideInMenu',
      title: '隐藏菜单',
      align: 'center',
      width: 80,
      render: row => {
        const hide: CommonType.YesOrNo = row.meta?.hideInMenu ? 'Y' : 'N';

        const tagMap: Record<CommonType.YesOrNo, NaiveUI.ThemeColor> = {
          Y: 'error',
          N: 'default'
        };
        const label = yesOrNoRecord[hide];

        return <NTag type={tagMap[hide]}>{label}</NTag>;
      }
    },
    {
      key: 'order',
      title: '排序',
      align: 'center',
      width: 80,
      render: row => row.meta?.order ?? '-'
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 230,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {row.menuType === '0' && (
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildMenu(row)}>
              新增子菜单
            </NButton>
          )}
          <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => '确认删除吗？',
              trigger: () => (
                <NButton type="error" ghost size="small">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(getData);

const operateType = ref<OperateType>('add');

function handleAdd() {
  operateType.value = 'add';
  openModal();
}

const routeStore = useRouteStore();

async function handleBatchDelete() {
  const { error } = await fetchDeleteMenu(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
  updateMenu();
}

async function handleDelete(id: number) {
  const { error } = await fetchDeleteMenu([id]);
  if (error) return;
  onDeleted();
  updateMenu();
}

const editingData: Ref<ManageApi.MenuManage.Menu | null> = ref(null);

function handleEdit(item: ManageApi.MenuManage.Menu) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}

function handleAddChildMenu(item: ManageApi.MenuManage.Menu) {
  operateType.value = 'addChild';
  editingData.value = { ...item };

  openModal();
}

function handleSubmite() {
  getData();
  updateMenu();
}

function updateMenu() {
  routeStore.resetStore();
  routeStore.initAuthRoute();
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="菜单配置列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          add-button
          batch-delete-button
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        class="sm:h-full"
      />
      <MenuOperateModal
        v-model:visible="visible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="handleSubmite"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
